package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.app.mess.NewBehaviorDTO;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.constants.article.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

/**
 * @author 29143
 */
@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 记录阅读行为
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {
//        1. 校验参数 文章id必须传
        //校验参数,判断文章id是否为空
        if (dto.getArticleId()==null) {
            log.error("文章id不能为空");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章id不能为空");
        }
//        2. 根据登录用户id 或 设备id查询行为实体数据(阅读操作可不登录)
        ApBehaviorEntry entry =new ApBehaviorEntry();

                //从线程中获取用户信息
        ApUser user = AppThreadLocalUtils.getUser();
        //判断当前用户是否登录
        if (user==null) {
            //当没有用户登陆时,根据设备id查询行为实体数据
            entry=apBehaviorEntryService.findByUserIdOrEquipmentId(null,dto.getEquipmentId());
        }
        //当用户登录时,根据用户id查询行为实体数据
        if (user!=null) {
            entry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), null);
        }
//        3. 判断阅读行为是否存在
        Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("entryId").is(entry.getId()));
        ApReadBehavior readBehavior = mongoTemplate.findOne(query, ApReadBehavior.class);
//        4. 存在  将阅读行为的count字段加1 并修改
        if (readBehavior!=null) {
            readBehavior.setCount((short) (readBehavior.getCount()+1));
            readBehavior.setReadDuration(dto.getReadDuration());
            readBehavior.setPercentage(dto.getPercentage());
            readBehavior.setLoadDuration(dto.getLoadDuration());
            mongoTemplate.save(readBehavior);
            return ResponseResult.okResult();
        }
//        5. 不存在  创建阅读行为 并初始化count字段值为 1
        readBehavior=new ApReadBehavior();
        readBehavior.setArticleId(dto.getArticleId());
        readBehavior.setEntryId(entry.getId());
        readBehavior.setCount((short) 1);
        readBehavior.setReadDuration(dto.getReadDuration());
        readBehavior.setPercentage(dto.getPercentage());
        readBehavior.setLoadDuration(dto.getLoadDuration());
        //保存信息
        mongoTemplate.save(readBehavior);
        // =======================新加代码==========================
        NewBehaviorDTO mess = new NewBehaviorDTO();
        mess.setType(NewBehaviorDTO.BehaviorType.VIEWS);
        mess.setArticleId(dto.getArticleId());
        mess.setAdd(1);
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(mess));
        log.info("点赞行为 发送消息 ==>{}",JSON.toJSONString(mess));
        // =======================新加代码==========================
        //返回结果信息
        return ResponseResult.okResult();
    }
}
